<template>
  <view>
    <view class="select-container page_bg_FAFAFA padd32">
      <template v-if="addressList.length !== 0">
        <uni-swipe-action>
          <view v-for="(item, index) in addressList" :key="item.id" @click="handleSelectAddress(item)">
            <uni-swipe-action-item :right-options="getOption(item)" @click="swipeActionClick" :auto-close="true">
              <view class="address-content">
                <view class="address-info">
                  <view class="name">
                    {{item.name}}
                  </view>
                  <view class="mobile">
                    {{item.phoneNumber}}
                  </view>
                  <view class="address-type" v-if="item.defaultStatus === 1">
                    默认地址
                  </view>
                </view>

                <view class="address">
                  {{item.deliveryAddress}}
                </view>
                <view class="arrow-right">
                  <u-icon name="arrow-right" color="#999999" size="18"></u-icon>
                </view>
              </view>
            </uni-swipe-action-item>
          </view>
        </uni-swipe-action>
      </template>


      <view v-else class="marginT140">
        <u-empty mode="address" icon="https://cdn.uviewui.com/uview/empty/address.png">
        </u-empty>
      </view>

    </view>
    <t-button @handleBtnClick="addAddress()" backGround="#FA312A" content="添加新地址"></t-button>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        addressList: [],
        addressInfo: {
          mobile: '',
          name: '',
          defaultAddress: '',
          deliveryAddress: '',
        },
        options: [{
            text: '删除', // 显示的文本内容
            style: {
              backgroundColor: '#C00000' // 按钮的背景颜色
            }
          },
          {
            text: '编辑', // 显示的文本内容
            style: {
              backgroundColor: '#ec9416' // 按钮的背景颜色
            }
          },
        ],

      };
    },
    onLoad(options) {

      this.getAddressAll()

    },
    methods: {
      getOption(item) {
        console.log('item222', item);
        return this.options.map(opt => {
            // 使用深拷贝创建选项的副本，而不是引用原始对象
             const optionCopy = JSON.parse(JSON.stringify(opt));
                optionCopy.data = JSON.parse(JSON.stringify(item));
                return optionCopy;
          });
        
      },
      handleSelectAddress(item) {
        uni.setStorageSync('addressInfo', item);
        uni.navigateBack();
      },

      async swipeActionClick(e) {
        console.log(e);
        const item = e.content
        if (item.text === '删除') {
          uni.showModal({
            title: '提示',
            content: '确认删除该地址？',
            confirmColor: '#C00000',
            success: async (res) => {
              if (res.confirm) {

                try {
                  const res = await this.$http.delete(
                    `/yaolexue-service-portal/receiveAddress/delReceiveAddressById/${item.data.id}`
                  );
                  if (res.code === 200) {
                    uni.showToast({
                      title: res.data
                    });
                    this.getAddressAll();
                  } else {
                    uni.showToast({
                      title: '删除失败',
                      icon: 'none'
                    });
                  }
                } catch (error) {
                  console.error('删除地址时发生错误:', error);
                  uni.showToast({
                    title: '删除失败',
                    icon: 'none'
                  });
                }
              }
            }
          });
        } else {
          uni.showModal({
              title: '提示',
              content: '确认修改该地址？',
              confirmColor: '#C00000',
              success: async (res) => {
                
                if (res.confirm) {
                  try {
                    const res = await this.$http.get(
                      `/yaolexue-service-portal/receiveAddress/receiveAddressInfoById/${item.data.id}`)
                      console.log(res, '1111111');
                    if (res.code !== 200) {
                      uni.showToast({
                        title: res.message,
                      });
                    } else {
                      getApp().globalData.addressInfo = res.data
                      uni.setStorageSync('addressInfo', res.data)
                      uni.redirectTo({
                        url: `/subPages/updatedAddress/updatedAddress?id=${item.data.id}`
                      })
                    }
                  } catch (e) {
                    console.log(e);
                  }

                }
              }

          })
        }
      },

      async getAddressAll() {
        try {
          uni.showLoading({
            title: '加载中...',
            mask: true
          });


          const res = await this.$http.get('/yaolexue-service-portal/receiveAddress/findReceiveAddressAll');


          uni.hideLoading();
          if (res.code === 200) {
            this.addressList = res.data;

            // 查找默认地址
            const defaultAddress = this.addressList.find(address => address.defaultStatus === 1);

            // 如果没有默认地址，将第一个地址存入本地
            if (!defaultAddress && this.addressList.length > 0) {
              const firstAddress = this.addressList[0];
              uni.setStorageSync('addressInfo', firstAddress);
              getApp().globalData.addressInfo = firstAddress
            } else {
              uni.setStorageSync('addressInfo', defaultAddress);
              getApp().globalData.addressInfo = defaultAddress
            }

            // 更新地址列表
            this.addressList = res.data;
          } else {
            uni.showToast({
              title: '获取地址列表失败',
              icon: 'none'
            });
          }
        } catch (error) {

          uni.hideLoading();

          console.error('获取地址列表时发生错误:', error);


          uni.showToast({
            title: '获取地址列表失败',
            icon: 'none'
          });
        }
      },
      
      addAddress() {

        uni.redirectTo({
          url: '/subPages/addAddress/addAddress'
        })
      }
    }
  }
</script>

<style lang="scss">
  .select-container {

    ::v-deep .uni-swipe_button-group {
      // height: 100px !important;
      margin-top: 21rpx;
      border: none !important;
    }

    .address-content {
      width: 689rpx;
      height: 152rpx;
      background: #FFFFFF;
      border-radius: 10rpx;
      margin-top: 21rpx;
      overflow: hidden;
      position: relative;


      .address-info {
        padding: 0 20rpx 0 38rpx;
        height: 39rpx;
        display: flex;
        margin-top: 28rpx;
        flex: 1;

        .name {
          min-width: 60rpx;

          font-size: 30rpx;
          font-family: Source Han Sans CN;
          font-weight: 400;
          color: #333333;
        }

        .mobile {
          min-width: 180rpx;

          font-size: 30rpx;
          font-family: Source Han Sans CN;
          font-weight: 400;
          color: #333333;
          margin: 0 21rpx 0 44rpx;
        }

        .address-type {
          width: 100rpx;
          height: 39rpx;
          line-height: 39rpx;
          background: rgba(250, 49, 42, .2);
          text-align: center;
          border-radius: 10rpx;
          font-size: 22rpx;
          font-family: Source Han Sans CN;
          font-weight: 400;
          color: rgba(250, 49, 42, 1);

        }
      }

      .address {
        width: 500rpx;

        margin-left: 39rpx;
        margin-top: 13rpx;

        min-height: 25rpx;
        font-size: 26rpx;
        font-family: Source Han Sans CN;
        font-weight: 400;
        color: #999999;
        word-break: break-word;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .arrow-right {
        position: absolute;
        right: 2%;
        top: 35%;
      }


    }




  }
</style>